package com.hx.base.action;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.hx.base.servlet.velocity.PageUtil;
import com.hx.common.Globals;
import com.hx.util.page.Page;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.ParameterNameAware;


public  class BaseAction extends ActionSupport implements ParameterNameAware{
	private static final long serialVersionUID = 1L;
	public static final String ADD = "add";
	public static final String SAVE = "save";
	public static final String SEARCH = "search";
	public static final String SEARCHDO = "searchDo";
	public static final String VIEW = "view";
	public static final String EDIT = "edit";
	public static final String FDEL = "fdel";
	public static final String CLEAN = "clean";
	public static final String ACTION_TYPE = "action_type";
	public static final String PAGE_NO = "pageNo";
	public static final int NO = 0;
	public static final String ORDER_BY = "orderStr";
	public static final String IS_DELETED = "isDeleted";
	/**
	 * Logger for this class
	 */
	protected static final Log log = LogFactory.getLog(BaseAction.class);
	public ServletContext context ;     
	
	public void setContext(ServletContext context) {
		this.context = context;
	}
    
	protected PageUtil pageutil = new PageUtil();
	
	/* 分页的路径 */
	//protected String pageUrl;

	public PageUtil getPageutil() {
		return pageutil;
	}

	public void setPageutil(PageUtil pageutil) {
		this.pageutil = pageutil;
	}

	/* 存放分页的结果集 */
	protected Page<?> pageObject = new Page<Object>();
	
	/* 当前页 */
	protected int pageNo = 1;

	/* 当前页显示记录数 */
	protected int pageSize = 10;
	
	/**
	 * 得到HttpServletResponse对象
	 * 
	 * @return
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 得到HttpServletRequest对象
	 * 
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	/**
	 * 得到ServletContext对象
	 * 
	 * @return
	 */
	protected ServletContext getServletContext() {
	  return ServletActionContext.getServletContext();
	}
	
	/**
	 * 得到HttpSession对象
	 * @return
	 */
	protected HttpSession getSession() {
	  return ServletActionContext.getRequest().getSession();
	}
	
	/**
	 * 获取request参数值
	 * @param key
	 * @return
	 * author:alex  20110523 下午 17：53    modify
	 * 当参数为空时  返回null  ibatiS查询null时才不会产生查询条件
	 * @throws UnsupportedEncodingException 
	 */
	protected String getParameter(String key){
	    return this.getRequest().getParameter(key);
	}
	/**
	 * 获取参数值
	 * 
	 * 这是个预留方法，现在URL编码在WEB服务器或应用服务器的
	 * CONNECTOR里进行配置
	 * 
	 * @author n.Die_Ssming 
	 * @param key  参数名称
	 * @param charsetName 编码名称
	 * @return  编码后的参数值
	 * @throws UnsupportedEncodingException  不支持的编码
	 */
	protected String getParameter(String key,String charsetName) throws UnsupportedEncodingException{
	    String s = this.getRequest().getParameter(key);
	    if(StringUtils.isNotEmpty(s))
	        return new String(s.getBytes("ISO-8859-1"),charsetName);
	    return "";
	}
	
	
	/**
	 * 获取request参数值
	 * @param key
	 * @return
	 */
	protected Object getAttribute(String key){
	    return this.getServletContext().getAttribute(key);
	}
	
	/**
	 * 获取request参数值
	 * @param key
	 * @return
	 */
	protected void setAttribute(String key,Object value){
	    this.getRequest().setAttribute(key,value);
	}
	/**
	 * 获取request参数值
	 * @param key
	 * @return
	 */
	protected String contain(String key){
	    return this.getRequest().getParameter(key);
	}
	
	/**
	 * 获取request参数值
	 * @param key
	 * @return
	 */
	protected String[] getParameters(String key){
	    return this.getRequest().getParameterValues(key);
	}
	
	/**
	 * 设置流信息
	 */
	protected void setStreamContentType(){
	    this.getResponse().setContentType("application/octet-stream");
	}
	
	/**
	 * 设置下载头信息
	 * @param fileName
	 */
	protected void setDownloadHeader(String fileName){
        try {
            this.getResponse().setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + new String(fileName.getBytes(), "iso-8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


   /**
	 * 不设置缓存
	 */
	protected void setNoCacheResponse() {
		HttpServletResponse response = this.getResponse();
		
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
	}


	public boolean acceptableParameterName(String parameterName) {
	   return true;
    }

	/**
	 * 清除cookie
	 */
	public void clearCookie()
	{
		Cookie[] cookies = this.getRequest().getCookies();
		if(null!=cookies){
			for(int i=0;i<cookies.length;i++)
			{
				Cookie c = cookies[i];
				if(c.getName().equals(Globals.USER_LOGIN_LICENSE_COOKIE))//过滤证书的cookie
					continue;
				c.setPath("/");
				c.setMaxAge(0);
				this.getResponse().addCookie(c);
			}
		}
	}
	/**
	 * 清除cookie
	 */
	public void removeCookie(String cookieName)
	{
		Cookie[] cookies = this.getRequest().getCookies();
		if(null!=cookies)
		{
			for(int i=0;i<cookies.length;i++)
			{
				Cookie c = cookies[i];
				if(null != c.getName() && c.getName().equals(cookieName))
				{
					c.setMaxAge(0);
					c.setPath("/");
					this.getResponse().addCookie(c);
					break;
				}
			}
		}
	}
	
	/**
	 * 增加cookie
	 * @param cookieKey
	 * @param cookieValue
	 */
	public void addCookie(String cookieKey,String cookieValue)
	{
		Cookie cookie = new Cookie(cookieKey,cookieValue);
		cookie.setPath("/");
		this.getResponse().addCookie(cookie);
	}
	
	/**
	 * 获取cookie里的值
	 * @param cookieName
	 * @return
	 */
	public String getCookieValue(String cookieName)
	{
		Cookie[] cookies = this.getRequest().getCookies();
		if(null!=cookies)
		{
			for(int i=0;i<cookies.length;i++)
			{
				Cookie c = cookies[i];
				if(null != c.getName() && c.getName().equals(cookieName))
				{
					return c.getValue();
				}
			}
		}
		return null;
	}
	
	/**
     * 判断用户的登陆状态
     * 用户注销与Cookie没有直接关系
       Cookie只有到期或用户手工删除
                  用户注销时，设置Cookie["login_state"]为"false"
                  用户登陆时，设置Cookie["login_state"]为"true"
     * 
     * @author n.Die_Ssming
     * @version [0.1,2011-4-12]
     * @see
     * @since 0.1
     * @return false:游客状态 ；true:登陆状态
     */
    public Boolean isLogin(){
        
        //表示用户登陆过,并非（删除Cookie之后）第一次登陆
        if(StringUtils.isNotEmpty(this.getCookieValue(Globals.SINGLE_LOGIN_USER_ID))){
            return Boolean.parseBoolean(this.getCookieValue(Globals.SINGLE_LOGIN_STATE));
        }
        return false;
    }
    /**
     * 获取Get方式传的ID集合
     * @param str 批量操作的id拼接字符串，如12-123-34
     * @param split 分隔符，如-
     * @return 
     */
    protected List<Integer> splitIDs(String str, String split) {
        List<Integer> list = new ArrayList<Integer>();
        if (str == null) {
            return list;
        }
        for (String id : str.split(split)) {
            list.add(Integer.parseInt(id));
        }
        return list;
    }

/*	public String getPageUrl() {
		return pageUrl;
	}

	public void setPageUrl(String pageUrl) {
		this.pageUrl = pageUrl;
	}*/

	public Page<?> getPageObject() {
		return pageObject;
	}

	public void setPageObject(Page<?> pageObject) {
		this.pageObject = pageObject;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
}
